<?php

namespace App\Http\Controllers;

use App\Http\Resources\CommentResource;
use App\Models\Comment;
use App\Http\Requests\StoreCommentRequest;
use App\Http\Requests\UpdateCommentRequest;
use App\Models\Topic;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CommentController extends Controller {
    public function __construct() {
        $this->middleware(['auth:sanctum'])->except(['index', 'show']);
    }

    /**
     * Display a listing of the resource.
     */
    public function index(Topic $topic) {
        $commets = $topic->comments()->whereNull('reply_comment_id')->with(['topic','reply_comments'])->get();
        return $this->success(data:CommentResource::collection($commets));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreCommentRequest $request, Topic $topic) {
        $comment = $topic->comments()->create(['user_id' => Auth::id()] + $request->input());
        return $this->success('评论新增成功', new CommentResource($comment->load(['topic', 'user', 'reply_comments', 'belong_to_comment', 'reply_user'])->refresh()));
    }

    public function replayComment(StoreCommentRequest $request, Topic $topic, Comment $comment) {
        $comment = $topic->comments()->create(
            [
                'user_id' => Auth::id(),
                'reply_comment_id'=>$comment->reply_comment_id ?: $comment->id,
                'reply_user_id'=>$comment->user_id
            ]
            +
            $request->input()
        );
        return $this->success('评论新增成功', new CommentResource($comment->load(['topic', 'user', 'reply_comments', 'belong_to_comment', 'reply_user'])->refresh()));

    }

    /**
     * Display the specified resource.
     */
    public function show(Comment $comment) {
        //
    }


    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Comment $comment) {
        $this->authorize('delete',$comment);
        $comment->delete();
        return $this->success('评论删除成功');
    }

    //获取某个人发的评论和回复
    public function getOneUserComments(User $user){
       $comments = Comment::with('user')->when(request('u_id'),function($query){
           return $query->where('user_id',request('u_id'));
       })->latest()->paginate(5);
       return CommentResource::collection($comments);
    }

    public function all_comments() {
        return CommentResource::collection(Comment::with(['topic'])->paginate(10));
    }
}
